package org.armstrong.ecoo.powertiles;

public class PowerTiler
{

    private int xDimension;
    private int yDimension;
    int largestPower;

    PowerTiler(int x, int y)
    {
        xDimension = x;
        yDimension = y;
        largestPower = largestPowerOfTwo();
    }

    public int calculateNumberOfTiles()
    {
        if ( smallerDimension() == 0 )
        {
            return 0;
        }
        if ( xDimension == yDimension && xDimension == largestPower )
        {
            return 1;
        }
    //    if (isPerfectRectangle())
  //      {
//            return largerDimension() / largestPower;
        //}
        PowerTiler tiler = new PowerTiler(largestPower *
                (int) Math.floor(largerDimension() / largestPower),
                                          smallerDimension() - largestPower);
        PowerTiler tiler2 = new PowerTiler(largerDimension() - (largestPower *
                (int) Math.floor(largerDimension() / largestPower)),
                                           largestPower);
        PowerTiler tiler3 = new PowerTiler(largerDimension() - (largestPower *
                (int) Math.floor(largerDimension() / largestPower)),
                                           smallerDimension() - largestPower);
        return tiler.calculateNumberOfTiles() + tiler2.calculateNumberOfTiles() + tiler3.calculateNumberOfTiles() +
                (int) Math.floor(largerDimension() / largestPower);
    }

    boolean isPerfectRectangle()
    {
        return largerDimension() % largestPower == 0;
    }

    public String properOutput(int numberOfTiles)
    {
        return String.format("%d tiles are needed for a %d by %d floor",
                             numberOfTiles,
                             xDimension, yDimension);
    }

    public boolean isPowerOfTwo(int dimension)
    {
        double log = Math.log10(dimension) / Math.log10(2);
        return Double.valueOf(1.0d).equals(log);
    }

    private int largestPowerOfTwo()
    {
        int smallerDimension = smallerDimension();
        int powerOfTwo = 1;
        while ( true )
        {
            if ( smallerDimension == powerOfTwo )
            {
                return powerOfTwo;
            }
            else
            {
                if ( powerOfTwo > smallerDimension )
                {
                    return powerOfTwo / 2;
                }
            }
            powerOfTwo *= 2;
        }
    }

    private int largerDimension()
    {
        return Math.max(xDimension, yDimension);
    }

    private int smallerDimension()
    {
        return Math.min(xDimension, yDimension);
    }
}
